const express = require('express');
const { Course, Membership, User, Order } = require('../../models');
const { NotFound, BadRequest } = require('http-errors');
const { failure, success } = require('../../utils/responses');
const { getKey, setKey } = require('../../utils/redis');
const router = express.Router();

const op = {
  attributes: { exclude: ['UserId'] },
  include: [
    {
      model: User,
      as: 'user',
      attributes: ['id', 'username', 'avatar'],
    },
  ],
};

/* 
查询用户订单
GET /orders */
router.get('/', async function (req, res) {
  try {
    const query = req.query;
    const currentPage = Math.abs(Number(query.currentPage)) || 1;
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    const offset = (currentPage - 1) * pageSize;
    const condition = {
      ...op,
      where: {},
      order: [['id', 'desc']],
      limit: pageSize,
      offset,
    };
    if (query.userId) {
      condition.where.userId = query.userId;
    }
    if (query.outTradeNo) {
      condition.where.outTradeNo = query.outTradeNo;
    }
    if (query.tradeNo) {
      condition.where.tradeNo = query.tradeNo;
    }
    if (query.status) {
      condition.where.status = query.status;
    }

    const { count, rows } = await Order.findAndCountAll(condition);
    success(res, '查询成功', {
      orders: rows,
      pagination: {
        total: count,
        currentPage,
        pageSize,
      },
    });
  } catch (error) {
    failure(res, error);
  }
});

/* 
查询用户订单详情
GET /orders */
router.get('/:outTradeNo', async function (req, res) {
  try {
    const order = await getOrder(req);
    success(res, '查询成功', { order });
  } catch (error) {
    failure(res, error);
  }
});

const getOrder = async (req) => {
  const { outTradeNo } = req.params;
  const order = await Order.findOne({
    ...op,
    where: {
      outTradeNo,
    },
  });

  if (!order) {
    throw new NotFound(`订单: ${outTradeNo} 的订单未找到`);
  }

  return order;
};

module.exports = router;
